<?php
namespace Manage\Model;
use Think\Model;
class AttributeModel extends Model{
	private $Model;
	function _initialize(){
		$this->Model=M('AttributeDescription');
	}
	public function operAttribute($data,$attribute_id=0){
		$attribute_data	=	$this->create($data);
		if($attribute_id){
			$this->where(array('attribute_id'=>$attribute_id))->save($attribute_data);
		}else{
			$attribute_id=$this->add($attribute_data);
		}
		$map['attribute_id']=$attribute_id;
		$this->Model->where($map)->delete();
		foreach ($data['attribute_description'] as $language_id => $attribute_description) {
			$attribute_description['language_id']=$language_id;
			$attribute_description['attribute_id']=$attribute_id;
			$this->Model->add($attribute_description);
		}
	}
	public function getById($attribute_id){
		$map['attribute_id']=$attribute_id;
		$return=$this->where($map)->find();
		$ag=$this->Model->where($map)->select();
		foreach ($ag as $v) {
			$return['attribute_description'][$v['language_id']]=$v;
		}
		return $return;
	}
	public function getAttributes($data=array()){
		$page=array(
			'start'		=>	$data['start']?$data['start']:0,
			'limit'		=>	$data['limit']?$data['limit']:C('CONFIG_LIMIT_MANAGE')
			);
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		if(isset($data['name'])) $map['name']=array("like","%".$data['name']."%");
		$order= 'sort_order ' . (isset($data['order'])?$data['order']:'ASC');
		$order .= ',attribute_group_id desc';
		$return=$this->join('LEFT JOIN __ATTRIBUTE_DESCRIPTION__ ON __ATTRIBUTE__.attribute_id=__ATTRIBUTE_DESCRIPTION__.attribute_id')->where($map)->order($order)->limit($page['start'],$page['limit'])->select();
		return $return;
	}
	public function getAll(){
		$map=array(
			'language_id'	=>	get_default_lng_id()
			);
		$order='sort_order ASC';
		$order .= ',attribute_group_id desc';
		$return=$this->join('LEFT JOIN __ATTRIBUTE_DESCRIPTION__ ON __ATTRIBUTE__.attribute_id=__ATTRIBUTE_DESCRIPTION__.attribute_id')->where($map)->order($order)->select();
		return $return;
	}
	public function getCount(){
		return $this->count();
	}
	public function del($attribute_id=0){
		$map['attribute_id']=$attribute_id;
		$PAModel = M('ProductAttribute');
		//删除商品属性表中与之相关的记录
		$PAModel->where($map)->delete();		
		//删除自身
		$this->Model->where($map)->delete();
		return $this->where($map)->delete();
	}
}